package model.User.controller;



import io.jsonwebtoken.Claims;
import model.User.entity.Result;
import model.User.entity.StatusCode;
import model.User.entity.User;
import model.User.service.IUserService;

import model.User.util.SMSCode;
import model.util.JwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.security.interfaces.RSAKey;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Sunshine、宸 on 2019/6/25.
 */
//@SuppressWarnings("all")
@RestController
public class UserController {
    @Autowired
    private IUserService iUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;



//    @GetMapping("/index")
//    public Result index(String username) {
////        String username=request.getParameter("username");
//        System.out.println(username+"11111111111111111111");
//        User user=null;
//        user.setUserName(username);
//        Result result = new Result(true, StatusCode.OK, "查询成功",user);
//        System.out.println(result);
//        return result;
//    }

    //根据用户名查找所有信息   用户名唯一@PathVariable("username") String username
//    @CrossOrigin
    @GetMapping("/userInformation/{username}")
    public Result user(@PathVariable("username") String username){
        Claims claims= (Claims) request.getAttribute("claims");
        System.out.println(username);
        if(null==claims){
            return  new Result(false,StatusCode.ACCESSERROR,"请先登录！");
        }else {
            User user = iUserService.findByUserName(username);
            Result result = new Result(true, StatusCode.OK, "查询成功", user);
//            System.out.println(result);
            return result;
        }
    }

    /**
     * 修改信息
     * @param user
     * @return
     */
    @GetMapping("/detail")
    public Result detail(User user){
        Result result=null;
        String username=user.getUserName();
        User u1=iUserService.findByUserName(username);

        System.out.println(u1);
        result=new Result(true,StatusCode.OK,"查询成功！",u1);

        return result;
    }

    @PutMapping("/changeAll")
    public Result changeAll(User user){
        Result result=null;
        String username=user.getUserName();
        System.out.println(username+"111");
        User u=iUserService.findByUserName(username);
        u.setUserPhone(user.getUserPhone());
        u.setUserBirth(user.getUserBirth());
        u.setUserBirthday(user.getUserBirthday());
        u.setUserEmail(user.getUserEmail());
        u.setUserAge(user.getUserAge());
        u.setUserJob(user.getUserJob());
        u.setUserLocation(user.getUserLocation());
        u.setUserCompany(user.getUserCompany());
        iUserService.updateByUser(u);
        System.out.println(u);
        result=new Result(true,StatusCode.OK,"修改成功！",u);

        return result;
    }


    @GetMapping("/inf/{userName}")
//    @PathVariable("userName") String userName
    public Result change( @PathVariable("userName") String userName){
        Result result=null;
//        iUserService.updateByUser(user);

        User u1=iUserService.findByUserName(userName);
        result=new Result(true,StatusCode.OK,"查询成功！",u1);

        return result;
    }


    /**
     * 修改密码
     * @param user
     * @return
     */
    @PostMapping("/password")
//    @CrossOrigin
    public Result u(User user){
        Result result=null;
        System.out.println(user);
        //前端数据
        String password=user.getUserPassword();
//        System.out.println(password);
        String confirmPassword=user.getUserConfirmpwd();
//        System.out.println(confirmPassword);
        String email=user.getUserEmail();
        String phone=user.getUserPhone();

        //如果前端密码和确认密码相同且不为空
        if(password.equals(confirmPassword)&&password!=null&&confirmPassword!=null){
            User user1=iUserService.findByEmail(user);
            String p1=bCryptPasswordEncoder.encode(password);
            String p2=bCryptPasswordEncoder.encode(confirmPassword);

            user1.setUserPassword(p1);
            user1.setUserConfirmpwd(p2);
             iUserService.updateByUser(user1);
             result=new Result(true,StatusCode.OK,"密码修改成功！");
        }else {
            result=new Result(true,StatusCode.ERROR,"密码修改失败！");
        }
        return result;
    }



    @GetMapping("/code2")
    public Result cc(User user){
        Result result=null;

        //接受前端的邮箱
        String email=user.getUserEmail();
        //查询后端的
        User user1=iUserService.findByEmail(user);
        System.out.println(user1);
//        String ema=user1.getUserEmail();
//        String ph=user1.getUserPhone();
        if(!email.equals("")) {
        if (user1 == null) {
            //随机产生6位数验证码
            String code = RandomStringUtils.randomNumeric(6);
            //把验证码放到session作用域中

            HtmlEmail el = new HtmlEmail();//创建一个HtmlEmail实例对象
            el.setHostName("smtp.qq.com");
            el.setCharset("utf-8");
            //rokwovlyrekrjffc
            //mvigjkrkouubhbcf

            el.setAuthentication(email,"rokwovlyrekrjffc");//设置发送人到的邮箱和用户名和授权码(授权码是自己设置的)
            try {
                el.addTo(email);//设置收件人
            } catch (EmailException e) {
                e.printStackTrace();
            }
            try {
                el.setFrom("1149490906@qq.com","home");//发送人的邮箱为自己的，用户名可以随便填
            } catch (EmailException e) {
                e.printStackTrace();
            }

            el.setSubject("欢迎使用,您的验证码为：");//设置发送主题
            try {
                el.setMsg(code);//设置发送内容
            } catch (EmailException e) {
                e.printStackTrace();
            }
            try {
                el.send();
            } catch (EmailException e) {
                e.printStackTrace();
            }
            result = new Result(true, StatusCode.OK, "邮箱发送成功！", code);

        } else {
            result = new Result(false, StatusCode.ERROR, "邮箱已存在！");
        }
    }else {
        result = new Result(false, StatusCode.ERROR, "邮箱为空！");
    }

        return result;
    }

    /**
     * 根据手机号或者邮箱获取验证码
     * @param user
     * @param req
     * @return
     */
    @GetMapping("/code")
//    @CrossOrigin
    public Result user(User user,HttpServletRequest req){
        Result result=null;
        //前端
       String email=user.getUserEmail();
       String phone=user.getUserPhone();

       //后端
        User user1=iUserService.findByEmail(user);
        String ema=user1.getUserEmail();
        String ph=user1.getUserPhone();


        if(user!=null){
            if(phone!=null) {
                if (phone.equals(ph)) {
//                    System.out.println(phone+"---------------");
                    user1.setUserFreeone(null);
                    iUserService.updateByUser(user1);
                    //随机产生6位数验证码
                    String code = RandomStringUtils.randomNumeric(6);
                    //把验证码放到session作用域中
//                    req.getSession().setAttribute("code", code);
                    user1.setUserFreeone(code);
                    iUserService.updateByUser(user1);
                    //发送验证码到手机
                    try {
                        SMSCode.sendCode(ph,code);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if(email!=null) {
                if (email.equals(ema)) {
//                    System.out.println(email+"++++++++++++++++++++");
                    user1.setUserFreeone(null);
                    iUserService.updateByUser(user1);
                    //随机产生6位数验证码
                    String code = RandomStringUtils.randomNumeric(6);
                    //把验证码放到session作用域中
//                    req.getSession().setAttribute("code", code);
                    user1.setUserFreeone(code);
                    iUserService.updateByUser(user1);

                    HtmlEmail el = new HtmlEmail();//创建一个HtmlEmail实例对象
                    el.setHostName("smtp.qq.com");
                    el.setCharset("utf-8");
                    el.setAuthentication(email, "mvigjkrkouubhbcf");//设置发送人到的邮箱和用户名和授权码(授权码是自己设置的)
                    try {
                        el.addTo(email);//设置收件人
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }
                    try {
                        el.setFrom("1142351748@qq.com", "lcy");//发送人的邮箱为自己的，用户名可以随便填
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }

                    el.setSubject("欢迎使用,您的验证码为：");//设置发送主题
                    try {
                        el.setMsg(code);//设置发送内容
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }
                    try {
                        el.send();
                    } catch (EmailException e) {
                        e.printStackTrace();
                    }
                } else {
                    result = new Result(false, StatusCode.ERROR, "邮箱不存在！", user1);
                }

            }else{
                result = new Result(false, StatusCode.ERROR, "邮箱为空！",user1);
            }
        }else {
            result = new Result(false, StatusCode.ERROR, "邮箱或手机为空！",user1);
        }
        return result;
    }

    /**
     * 找回密码
     * @param u
     * @return
     */
    @GetMapping("/c")
//    @CrossOrigin
    public Result use(User u) {
//        System.out.println(u);
        Result result=null;
        //获取前端
        String email=u.getUserEmail();
        String phone=u.getUserPhone();
        String freeOne=u.getUserFreeone();

        //数据库
        String pattern1 =  "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        //手机
        String REGEX_MOBILE = "(134[0-8]\\d{7})" + "|(" + "((13([0-3]|[5-9]))" + "|149" + "|15([0-3]|[5-9])" + "|166" + "|17(3|[5-8])" + "|18[0-9]" + "|19[8-9]" + ")" + "\\d{8}" + ")";

        //如果前端传过来的数据不为null
        if(u!=null){
            if(phone!=null){
                if(phone.matches(REGEX_MOBILE)){
                    User user=iUserService.findByEmail(u);
                    String ph=user.getUserPhone();
                    String em=user.getUserEmail();
                    String freeCode= user.getUserFreeone();
                    System.out.println(freeCode);
                    if(phone.equals(ph)&&freeOne.equals(freeCode)){

                        result=new Result(true, StatusCode.OK,"验证码正确！",user);
                        user.setUserFreeone(null);
                        iUserService.updateByUser(user);
                    }else{
                        result = new Result(false,StatusCode.LOGINERROR,"重置失败,验证码错误!");
                    }
                }else {
                    result = new Result(false, StatusCode.ErrorPhone, "重置失败,手机号不存在!");
                }
            }else if(email.matches(pattern1)){

                User user=iUserService.findByEmail(u);
                String ph=user.getUserPhone();
                String em=user.getUserEmail();
                String freeCode= user.getUserFreeone();
//                System.out.println(freeCode);

                    if(email.equals(em)&&freeOne.equals(freeCode)){

                        result=new Result(true, StatusCode.OK,"成功！",user);
                        user.setUserFreeone(null);
                        iUserService.updateByUser(user);

                    }else{
                        result = new Result(false,StatusCode.LOGINERROR,"重置失败,验证码错误!");
                    }
                }else {
                    result = new Result(false, StatusCode.EmailError, "登录失败,邮箱不存在!");
                }

        }else {
            result = new Result(false, StatusCode.ERROR, "登录失败,手机号或邮箱为空!");
        }
        return result;
    }

    /**
     * 注册要判断邮箱 电话   是否存在  如果存在提示邮箱或者电话已经存在
     * @param
     * @param
     * @return
     */

    @PostMapping("/reg")
//    @CrossOrigin
    public Result result1(User user){
        Result result=null;
        //获取前端
        String username=user.getUserName();
        String email=user.getUserEmail();
        String phone=user.getUserPhone();
        String password=user.getUserPassword();
        String confirmPwd=user.getUserConfirmpwd();
        String code1=user.getUserFreeone();
        String code2=user.getUserFreetwo();

//        System.out.println(user);
        //后端
        User u =iUserService.findByEmail(user);

        //判断u是否为空
        if(null==u) {
            //如果u为空 说明没有此用户 可以进行保存   如果验证码相同
            if(code1.equals(code2)) {
                if(password.equals(confirmPwd)){
                if (username != "" && email != "" && phone != "" && password != "" && confirmPwd != "") {
                    String p1=bCryptPasswordEncoder.encode(password);
                    String p2=bCryptPasswordEncoder.encode(confirmPwd);
                    user.setUserPassword(p1);
                    user.setUserConfirmpwd(p2);
                    iUserService.Save(user);
                    result = new Result(true, StatusCode.OK, "注册成功！", user);
                }
                else {
                    result = new Result(false, StatusCode.ERROR, "请完善所有信息！", user);
                }
            }else {
                    result = new Result(false, StatusCode.ERROR, "两次密码不一致！");
                }
            }  else {
                result = new Result(false, StatusCode.ERROR, "验证码错误！");
            }



        }else if(null!=u){
            String em=u.getUserEmail();
            String ph=u.getUserPhone();
            if(phone.equals(ph)&&!email.equals(em)){
                result=new Result(false,StatusCode.ERROR,"手机号已经存在！");
            }else if(!phone.equals(ph)&&email.equals(em)){
                result=new Result(false,StatusCode.ERROR,"邮箱已经存在！");
            }else if(user.getUserName().equals(u.getUserName())&&user.getUserName()!=null){
                result=new Result(false,StatusCode.ERROR,"用户名已经存在！");
            } else {
                result=new Result(false,StatusCode.ERROR,"邮箱和手机号已经存在！");
            }
        }

        return result;
    }


    /**
     * 登陆
     * @param u
     * @param request
     * @return
     */


//    @CrossOrigin()
    @PostMapping("/user")
    public Result result(User u,HttpServletRequest request){


//        Claims claims= (Claims) request.getAttribute("claims");
        Boolean flag=bCryptPasswordEncoder.matches("1","1");
//        System.out.println(flag);
        //u是前端传过来的数据
        String phone=u.getUserPhone();
        String email=u.getUserEmail();
        String password=u.getUserPassword();



        //数据库
        User user=iUserService.findByEmail(u);
        System.out.println(user.getUserName());
        System.out.println(user.getUserId());
        String ph=user.getUserPhone();
        String em=user.getUserEmail();
        String pwd=user.getUserPassword();
        //邮箱
        String pattern1 =  "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        //手机
        String REGEX_MOBILE = "(134[0-8]\\d{7})" + "|(" + "((13([0-3]|[5-9]))" + "|149" + "|15([0-3]|[5-9])" + "|166" + "|17(3|[5-8])" + "|18[0-9]" + "|19[8-9]" + ")" + "\\d{8}" + ")";

        Result result=null;

//        System.out.println(claims+"====");

        //
//        if(null!=claims){
//
//            result = new Result(false,StatusCode.ERROR,"您已登陆！");
//        }else {

            //如果前端传过来的数据不为null
            if (u != null) {
                if (phone != null) {
                    if (phone.matches(REGEX_MOBILE)) {
//                    if(phone.equals(ph)&&password.equals(pwd)){
                        //bCryptPasswordEncoder.matches(password,pwd)
                        if (phone.equals(ph) && bCryptPasswordEncoder.matches(password, pwd)) {
                            //如果正确登陆 返回token
                            String token = jwtUtil.createJWT(String.valueOf(u.getUserId()), u.getUserName(), "admin");
                            Map<String, Object> maps = new HashMap();
                            maps.put("username", u.getUserName());
                            maps.put("token", token);
                            request.setAttribute("username",u.getUserName());
                            result = new Result(true, StatusCode.OK, "登录成功！", maps);
                        } else {
                            result = new Result(false, StatusCode.LOGINERROR, "登录失败,密码错误!");
                        }
                    } else {
                        result = new Result(false, StatusCode.ErrorPhone, "登录失败,手机号不存在!");
                    }
                } else {
                    if (email.matches(pattern1)) {
                        System.out.println(password);
                        System.out.println(pwd);
                        System.out.println(password.equals(pwd));
//                    Boolean flag=bCryptPasswordEncoder.matches(password,pwd);
                        System.out.println(flag);
                        //bCryptPasswordEncoder.matches(password,pwd)
                        if (email.equals(em) && bCryptPasswordEncoder.matches(password, pwd)) {
                            String token = jwtUtil.createJWT(String.valueOf(user.getUserId()), user.getUserName(), "admin");
                            Map<String, Object> maps = new HashMap();
                            maps.put("userName", user.getUserName());
                            maps.put("token", token);

                            result = new Result(true, StatusCode.OK, "用户登录成功！", maps);
                        } else {
                            result = new Result(false, StatusCode.LOGINERROR, "用户登录失败,密码错误!");
                        }
                    } else {
                        result = new Result(false, StatusCode.EmailError, "登录失败,邮箱不存在!");
                    }
                }
            } else {
                result = new Result(false, StatusCode.ERROR, "登录失败,手机号或邮箱为空!");
            }
//        }

        return result;
    }

}
